package com.ydlclass.serialize.Factory;

import com.ydlclass.serialize.Impl.HessianSerializer;
import com.ydlclass.serialize.Impl.JdkSerializer;
import com.ydlclass.serialize.Impl.JsonSerializer;
import com.ydlclass.serialize.SerializeWrapper;
import com.ydlclass.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 序列化工厂方法
 * @Author duWenJian
 * @Date 2023/11/3 14:28
 * @Version 1.0
 */
@Slf4j
public class SerializeFactory {
    private final static ConcurrentHashMap<String, SerializeWrapper> SERIALIZE_CACHE = new ConcurrentHashMap<>(8);
    private final static ConcurrentHashMap<Byte, SerializeWrapper> SERIALIZE_CACHE_CODE = new ConcurrentHashMap<>(8);
    static {
        SerializeWrapper jdk = new SerializeWrapper((byte) 1,"jdk",new JdkSerializer());
        SerializeWrapper json = new SerializeWrapper((byte) 2,"json",new JsonSerializer());
        SerializeWrapper Hessian = new SerializeWrapper((byte) 3,"hessian",new HessianSerializer());
        SERIALIZE_CACHE.put("jdk", jdk);
        SERIALIZE_CACHE.put("json", json);
        SERIALIZE_CACHE.put("hessian", Hessian);
        SERIALIZE_CACHE_CODE.put(jdk.getCode(), jdk);
        SERIALIZE_CACHE_CODE.put(json.getCode(), json);
        SERIALIZE_CACHE_CODE.put(Hessian.getCode(), Hessian);
    }

    /**
     * 使用工厂方法，获取一个SerializeWrapper
     * @param serializeType 序列化的类型
     * @return
     */
    public static SerializeWrapper getSerializer(String serializeType) {
        SerializeWrapper serializeWrapper = SERIALIZE_CACHE.get(serializeType);
        if (serializeWrapper == null) {
            if (log.isDebugEnabled()){
                log.debug("序列化类型不存在，使用默认的jdk序列化");
            }
            return SERIALIZE_CACHE.get("jdk");
        }
        return SERIALIZE_CACHE.get(serializeType);
    }
    public static SerializeWrapper getSerializer(byte serializeType) {
        SerializeWrapper serializeWrapper = SERIALIZE_CACHE_CODE.get(serializeType);
        if (serializeWrapper == null) {
            if (log.isDebugEnabled()){
                log.debug("序列化类型不存在，使用默认的jdk序列化");
            }
            return SERIALIZE_CACHE_CODE.get((byte) 1);
        }
        return SERIALIZE_CACHE_CODE.get(serializeType);
    }

}
